<template>
	<!-- 菜单选择 -->
	<view class="">
		<view class="u-menu-wrap" :style="{'height':warpperHeight+'px'}">
			<scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop"
				:scroll-into-view="itemId">
				<view class="df" style="flex-direction: column;">
					<view v-for="(item,index) in tabbar" :key="index" class="u-tab-item"
						:class="[current == index ? 'u-tab-item-active' : '']" @tap.stop="swichMenu(index)">
						<view class="u-text-center">
							<view class="u-line-1 mt10">{{item.subjectName||item.categoryName}}</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="pr" style="height: inherit;width: 577rpx;background-color: white;">
				<view class="u-text-center pt20 " style="width: 537rpx;margin: 0 auto;" v-if="bannerList.length">
					<u-swiper :mode="bannerList.length===1?'none':'round'" :list="bannerList" @click='clickBanner'
						height="110"></u-swiper>
				</view>
				
				<!-- 二级分类 -->
				<view class="category df aic jcsb p20">
					<scroll-view scroll-x style="width: 100%;">
						<view class="category-box df aic ">
							<view v-for="(item,index) in tabbarThree" class="category-item"
							@tap.stop="swichMenuThree(index)"
								:class="{'category-item-current':currentSubject==index}">
								{{item.subjectName}}
							</view>
						</view>
					</scroll-view>
					<!-- <nmr-icon name="xiajiantou" color="#666666" size="28"></nmr-icon> -->
				</view>
				<!-- 需要计算高度 -->
				<scroll-view :style="{'height':warpperHeightRight+'px'}" @scrolltolower="scrolltolower"
					:scroll-top="scrollRightTop" scroll-y scroll-with-animation class="right-box" @scroll="rightScroll">
					<view class="page-view">
						<ourLoading :active="logingSubject" translateY="50" color="#48A147" background-color="white" size="4"></ourLoading>
						<view class="class-item">
							<view class="item-container">
								<view v-if="menuGoods.length==0" class="df aic jcc"
									style="flex-direction: column;width: 100%; " :style="{'height':warpperHeightRight+'px'}" >
									<image src="@/static/empty/content-empty.png" style="width: 300rpx;height: 156rpx;"
										mode="widthFix"></image>
									<view class="c9 fs28 ">
										暂无商品
									</view>
								</view>
								<!--  -->
								<!--  -->
								<view  v-else class="df item-container-item mb20" v-for="(item1, index1) in menuGoods" :key="index1" >
									<view class="pr" style="height: 150rpx;" @tap="handleSku(item1)">
											<u-image :src="item1.platformGoodsSpecMix&&item1.platformGoodsSpecMix[0].image.split(',')[0]" border-radius="10" width="150rpx"
											height="150rpx"></u-image>
										<view class="empty-img-sale df aic jcc"
											v-if="item1.saleStock<=0&&item1.saleType!=2">
											<view class="sale-no-box">
												补货中
											</view>
										</view>
									</view>
									<view class="ml20 info-box" style="">
										<view class="title u-line-2" @tap="handleSku(item1)">
											{{item1&&item1.customGoodsName}}
										</view>
										
										<view class="mt10 "  >
											<view class="goodsLabel">
												{{item1.platformGoodsSpecMix&&item1.platformGoodsSpecMix[0].specName}}
											</view>
										</view>
										<view class="fs22 c9 fw4 mt10 p010 textOver" style="width: 400rpx;" >
											{{item1.introduce||''}}
										</view>
										<view  class="df aic price  fwb mt10" v-if="TOKEN&&item1.referencePriceRange && item1.referencePriceRange!='0.00' &&$common.calcTime(item1.startTime,item1.endTime)">
											<text class="fs24">单价:</text> <text
												class="fs28">{{item1.referencePriceRange}}</text>
										</view>
										<view class="mt10 df   jcsb pr">
											<view class="price-box " v-if="TOKEN">
												<Vip class="mr5" v-if="item1.priceRangeOne&&TOKEN&&((item1.platformGoodsSpecMix.length==1&&!item1.platformGoodsSpecMix[0].purNum>0))&&$common.calcTime(item1.startTime,item1.endTime)"></Vip>
												<text class="price fwb">￥{{$common.calcTime(item1.startTime,item1.endTime)?item1.priceRange||0:'待报价'}}</text>
												<!-- <text class="unit c3 fs24">/{{item1&&item1.saleUnit}}</text> -->
												<!-- <text class="old-price">￥10.0</text> -->
											</view>
											<view class="price-box " v-else>
												<text class="price fwb">登录可见价格</text>
											</view>
											<!-- #ifndef APP-PLUS -->
											<nmr-icon v-if="!TOKEN && ($common.calcTime(item1.startTime,item1.endTime))" @click="handleLogin" name="jiatianjia-yuankuang" size="40"
												color="#47A848"></nmr-icon>
											<view class="pr" style="right: 32rpx;" v-else>
												<u-badge v-if="item1.platformGoodsSpecMix.length!=1 &&($common.calcTime(item1.startTime,item1.endTime))" absolute :offset="[-13,-22]" size="mini"
													:count="checkNum(item1)" type="error">
												</u-badge>
												<view class="" v-if="$common.calcTime(item1.startTime,item1.endTime)">
													<zm-number-box 
													:saleUnit="item1.platformGoodsSpecMix[0].saleUnit"
													:startSaleNum="item1.platformGoodsSpecMix[0].startSaleNum" :step="item1.platformGoodsSpecMix[0].startSaleNum&&item1.platformGoodsSpecMix[0].isDouble==1?item1.platformGoodsSpecMix[0].startSaleNum:1" :disabledInput="item1.platformGoodsSpecMix[0].isDouble==1" 
													v-if="item1.platformGoodsSpecMix.length==1 " size="40" @change="valChange($event,item1)"
														:min="0" v-model="item1.platformGoodsSpecMix[0].purNum" v-else></zm-number-box>
													<!-- 多规格的情况下 需要选择规格 -->
													<!-- <nmr-icon v-else @click="chooseSkuShow(item1,index1)" name="jiatianjia-yuankuang" size="40"
														color="#47A848"></nmr-icon> -->
														<view class="fs22 df aic jcc spce-box"  v-else @click="chooseSkuShow(item1,index1)">
															选规格
														</view>
												</view>
												
											</view>
											<!-- #endif -->
										</view>
										<text class="text-under c9 fs24 ml5" v-if="item1.priceRangeOne&&TOKEN&&$common.calcTime(item1.startTime,item1.endTime)">原价:￥{{item1.priceRangeOne}}</text>
									</view>
								</view>
								<u-loadmore style="width: 100%;" v-if="menuGoods.length!=0" margin-top="20"
									margin-bottom="30" :status="loadStatus" :load-text="loadText" />
							</view>
						</view>
					</view>
				</scroll-view>

			</view>

		</view>
		<SkuPopup @changeCarList="changeCarList" :goodsCarList="cartList" @change="changeSku" v-model="showSku" :info="skuInfo" ></SkuPopup>
	</view>
</template>
<script>
	import {bGroupCategoryList,bGroupCategoryGoods} from '@/api/bGroupCategory.js'
	import ourLoading from '@/components/our-loading/our-loading.vue'
	import SkuPopup from '../../../components/SkuPopup/SkuPopup.vue'
	import {
		queryTopBSubjectList,
		platformGoodsList
	} from '@/api/goods.js'
	export default {
		components: {
			ourLoading,
			SkuPopup
		},
		props: {
			warpperHeight: {
				default: 10000,
				type: [String, Number]
			},
			warpperHeightRight: {
				default: 10000,
				type: [String, Number]
			},
			bannerList: {
				default: () => [],
				type: Array
			},
			cartList: {
				default: () => [],
				type: Array
			},
			type:'',
			platformGroupId:''
		},
		data() {
			return {
				showSku: false,
				skuInfo:{},
				scrollTop: 0, //tab标题的滚动条位置
				oldScrollTop: 0,
				current: 0, // 预设当前项的值
				menuHeight: 0, // 左边菜单的高度
				menuItemHeight: 0, // 左边菜单item的高度
				itemId: '', // 栏目右边scroll-view用于滚动的id
				tabbar: [],
				tabbarThree:[],
				arr: [],
				scrollRightTop: 0, // 右边栏目scroll-view的滚动条高度
				timer: null, // 定时器
				menuGoods: [],
				loadStatus: 'loadmore',
				pageNum: 1,
				pageSize: 40,
				loadText: {
					loadmore: '轻轻上拉',
					loading: '努力加载中',
					nomore: '没有更多了'
				},
				subjectId: '',
				UNI_Platform_VALUE_TYPE: '',
				logingSubject:false,
				currentSubject:0,
				currentIndexGoods:0,
				parentSubjectId:''
			}
		},
		mounted() {
			this.UNI_Platform_VALUE_TYPE = this.UNI_Platform_VALUE

		},
		methods: {
			valChange(e, item) {
				this.$set(item.platformGoodsSpecMix[0], 'purNum', e)
				this.handleCart(item.platformGoodsSpecMix[0])
			},
			handleCart(e) {
				let goodsCarList = this.cartList||[]
				let index = goodsCarList.findIndex(i => i.platformGoodsSpecMixId == e.platformGoodsSpecMixId)
				if (index == -1) { //购物车中没有这个商品  新增操作
					goodsCarList.unshift(e)
				} else { //购物车中有这个商品  修改操作
					if (e.purNum == 0) { //删除操作
						goodsCarList.splice(index, 1)
					} else {
						//只有購物車的時候 才手動更新列表
						goodsCarList[index].purNum = e.purNum
						goodsCarList[index].busType = ''
						goodsCarList[index].platformPrice = e.platformPrice
					}
				}
				this.$emit('changeCarList',goodsCarList)
			},
			changeCarList(e){
				this.$emit('changeCarList',e)
			},
			changeSku(info){
				this.menuGoods[this.currentIndexGoods] = info
			},
			chooseSkuShow(item,index) {
				this.currentIndexGoods = index
				this.skuInfo = item
				this.showSku = true
			},
			clacGoods(list){
				return new Promise((resolve,reject) =>{
					list.forEach(e => {
						e.platformGoodsSpecMix.forEach(mix =>{
							let info = this.cartList.find(_e => _e.platformGoodsSpecMixId === mix
								.platformGoodsSpecMixId)
							if (info) {
								this.$set(mix,'purNum',info.purNum)
								this.$set(mix,'checkFlag',true)
							}else{
								this.$set(mix,'purNum',0)
								this.$set(mix,'checkFlag',true)
							}
						})
						
					})
					resolve(list)
				})
			},
			checkNum(item){
				let numAll = 0
				item.platformGoodsSpecMix.forEach(i => {
								numAll+= i.purNum
				})
				return numAll
			},
			handleLogin() {
				this.$emit('handleLogin')
			},
			clickBanner(e) {
				this.$common.advJump(this.bannerList[e])
			},

			getMenuHandle(e) {
				console.log('fuji',e)
				if(this.parentSubjectId==e)return
				if(this.logingSubject||this.loadStatus=='loading')return
				this.parentSubjectId = e
				console.log('this.parentSubjectId',this.parentSubjectId)
				this.logingSubject = true
				this.current = 0
				this.currentSubject = 0
				this.init()
				this.getMenu(e)
			},
			clear() {
				this.menuGoods.forEach(e => {
					e.purNum = 0
				})
			},
			calcPurNum(i, num) {
				this.menuGoods.forEach(e => {
					if (e.platformGoodsSpecMixId === i.platformGoodsSpecMixId)
						e.purNum = num
				})
			},
			scrolltolower() {
				if(this.type=="scene"){
					if(!this.tabbar.length)return
					this.getGoodsListScene(this.tabbar[this.current].categoryId)
				}else{
					console.log(this.subjectId,'this.subjectId')
					this.getGoodsList(this.subjectId)
				}
			},
			init() {
				this.loadStatus = 'loadmore'
				this.pageNum = 1
				this.pageSize = 40
				this.menuGoods = []
			},
			
			getMenuScene() {
				this.logingSubject = true
				bGroupCategoryList({platformGroupId:this.platformGroupId}).then(res => {
					this.tabbar = []
					this.tabbar.push(...res.data)
					if(this.tabbar.length){
						this.getMenuItemTop()
						this.init()
						this.getGoodsListScene(this.tabbar[0].categoryId)
					}else{
						this.logingSubject = false
					}
					
				})
			},
			// 获取二级分类
			getMenu(e) {
				queryTopBSubjectList({
					isShowB: 0,
					parentId:e
				}).then(res => {
					this.tabbar = []
					this.tabbar.push(...res)
					if(res.length){
						this.getMenuItemTop()
						this.getThreeMenu(this.tabbar[0].subjectId)
					}else{
							this.loadStatus = 'nomore'
							this.logingSubject = false
					}
				})
			},
			// 获取三级
			getThreeMenu(e) {
				this.logingSubject = true
				queryTopBSubjectList({
					isShowB: 0,
					parentId:e
				}).then(res => {
					this.tabbarThree = []
					this.tabbarThree.push(...res)
					this.init()
					if(res.length){
					this.subjectId = this.tabbarThree[0].subjectId
					this.getGoodsList(this.tabbarThree[0].subjectId)
					}else{
							this.loadStatus = 'nomore'
							this.logingSubject = false
					}
					
				})
			},
			async clacGoodsSet(){
				if(!this.menuGoods.length)return
				let list  = await this.clacGoods(this.menuGoods)
				this.menuGoods = list
			},
			getGoodsListScene(e) {
				if (this.loadStatus == 'nomore' || this.loadStatus == 'loading') return
				this.loadStatus = 'loading'
				bGroupCategoryGoods({
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					bPlatformGroupCategoryId: e
				}).then(async res => {
					if (res.code == 200) {
						this.logingSubject = false
						let list = await this.clacGoods(res.rows)
						this.menuGoods.push(...list)
						this.pageNum = ++this.pageNum;
						if (res.rows.length < this.pageSize) {
							this.loadStatus = 'nomore' //不用加载下一页
						} else {
							this.loadStatus = 'loadmore' //不用加载下一页
						}
					} else {
						this.loadStatus = 'nomore'
						uni.showToast({
							title: res.msg,
							icon: "none",
						});
					}
				}).catch(() =>{
					this.loadStatus = 'nomore'
					this.logingSubject = false
				})
			},
			getGoodsList(e) {
				if (this.loadStatus == 'nomore' || this.loadStatus == 'loading') return
				this.loadStatus = 'loading'
				platformGoodsList({
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					subjectId: e,
					flag:'normal'
				}).then(async res => {
					if (res.code == 200) {
						this.logingSubject = false
						let list = await this.clacGoods(res.rows)
						this.menuGoods.push(...list)
						this.pageNum = ++this.pageNum;
						if (res.rows.length < this.pageSize) {
							this.loadStatus = 'nomore' //不用加载下一页
						} else {
							this.loadStatus = 'loadmore' //不用加载下一页
						}
					} else {
						this.loadStatus = 'nomore'
						uni.showToast({
							title: res.msg,
							icon: "none",
						});
					}
				}).catch(() =>{
					this.loadStatus = 'nomore'
					this.logingSubject = false
				})
			},
			handleSku(e) {
				uni.navigateTo({
					url: '/pages/goods/detail?id=' + e.platformGoodsId 
				})
			},
		
			// 切换第三级菜单 直接获取商品
			swichMenuThree(index){
				if (this.loadStatus === 'loading') return
				console.log(index , this.currentSubject,index == this.currentSubject,'==========')
				if (index == this.currentSubject) return;
				this.logingSubject = true
				this.currentSubject = index
				this.init()
				if(this.tabbarThree.length){
					this.getGoodsList(this.tabbarThree[this.currentSubject].subjectId)
				}else{
					this.loadStatus = 'nomore'
					this.logingSubject = false
				}
				
				
			},
			// 点击左边的栏目切换
			async swichMenu(index) {
				if (this.loadStatus === 'loading') return
				this.subjectId = this.tabbar[index].subjectId
				this.currentSubject = 0
				if (this.arr.length == 0) {
					await this.getMenuItemTop();
				}
				if (index == this.current) return;
				this.scrollRightTop = this.oldScrollTop;

				this.$nextTick(function() {
					this.scrollRightTop = 0;
					this.current = index;
					this.init()
					if(this.type=='scene'){
						this.logingSubject = true
						this.getGoodsListScene(this.tabbar[index].categoryId)
					}else{
						this.getThreeMenu(this.tabbar[index].subjectId)
						this.leftMenuStatus(index);
					}
					
				})
			},
			// 获取一个目标元素的高度
			getElRect(elClass, dataVal) {
				new Promise((resolve, reject) => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.' + elClass).fields({
						size: true
					}, res => {
						// 如果节点尚未生成，res值为null，循环调用执行
						if (!res) {
							setTimeout(() => {
								this.getElRect(elClass);
							}, 10);
							return;
						}
						this[dataVal] = res.height;
						resolve();
					}).exec();
				})
			},
			// // 观测元素相交状态
			// async observer() {
			// 	this.tabbar.map((val, index) => {
			// 		let observer = uni.createIntersectionObserver(this);
			// 		// 检测右边scroll-view的id为itemxx的元素与right-box的相交状态
			// 		// 如果跟.right-box底部相交，就动态设置左边栏目的活动状态
			// 		observer.relativeTo('.right-box', {
			// 			top: 0
			// 		}).observe('#item' + index, res => {
			// 			if (res.intersectionRatio > 0) {
			// 				let id = res.id.substring(4);
			// 				this.leftMenuStatus(id);
			// 			}
			// 		})
			// 	})
			// },
			// 设置左边菜单的滚动状态
			async leftMenuStatus(index) {
				this.current = index;
				// 如果为0，意味着尚未初始化
				if (this.menuHeight == 0 || this.menuItemHeight == 0) {
					await this.getElRect('menu-scroll-view', 'menuHeight');
					await this.getElRect('u-tab-item', 'menuItemHeight');
				}
				// 将菜单活动item垂直居中
				this.scrollTop = index * this.menuItemHeight + (uni.upx2px(18 + 75)) / 2 - this.menuHeight / 2
			},
			// 获取右边菜单每个item到顶部的距离
			getMenuItemTop() {
				new Promise(resolve => {
					let selectorQuery = uni.createSelectorQuery();
					selectorQuery.selectAll('.class-item').boundingClientRect((rects) => {
						// 如果节点尚未生成，rects值为[](因为用selectAll，所以返回的是数组)，循环调用执行
						if (!rects.length) {
							setTimeout(() => {
								this.getMenuItemTop();
							}, 10);
							return;
						}
						rects.forEach((rect) => {
							// 这里减去rects[0].top，是因为第一项顶部可能不是贴到导航栏(比如有个搜索框的情况)
							this.arr.push(rect.top - rects[0].top);
							resolve();
						})
					}).exec()
				})
			},
			// 右边菜单滚动
			async rightScroll(e) {
				this.oldScrollTop = e.detail.scrollTop;
				if (this.arr.length == 0) {
					await this.getMenuItemTop();
				}
				if (this.timer) return;
				return
				if (!this.menuHeight) {
					await this.getElRect('menu-scroll-view', 'menuHeight');
				}
				setTimeout(() => { // 节流
					this.timer = null;
					// scrollHeight为右边菜单垂直中点位置
					let scrollHeight = e.detail.scrollTop + this.menuHeight / 2;
					for (let i = 0; i < this.arr.length; i++) {
						let height1 = this.arr[i];
						let height2 = this.arr[i + 1];
						// 如果不存在height2，意味着数据循环已经到了最后一个，设置左边菜单为最后一项即可
						if (!height2 || scrollHeight >= height1 && scrollHeight < height2) {
							this.leftMenuStatus(i);
							return;
						}
					}
				}, 10)
			}

		}
	}
</script>

<style lang="scss" scoped>
	.category-box {
		.category-item {
			padding: 7rpx 16rpx;
			background-color: #F1F1F1;
			color: #666666;
			font-size: 24rpx;
			margin-right: 20rpx;
			border-radius: 10rpx 10rpx 10rpx 10rpx;
			flex-shrink: 0;
		}

		.category-item-current {
			padding: 7rpx 16rpx;
			background: #ECFFEB;
			color: #48A147;
			font-size: 24rpx;
		}
	}

	.menu-scroll-view {
		background: #ECFFEB;
		box-shadow: inset 0rpx 0rpx 4rpx 1rpx rgba(72, 161, 71, 0.19);
	}


	.u-menu-wrap {
		flex: 1;
		display: flex;
		overflow: hidden;
	}

	.u-search-inner {
		background-color: rgb(234, 234, 234);
		border-radius: 100rpx;
		display: flex;
		align-items: center;
		padding: 10rpx 16rpx;
	}

	.u-search-text {
		font-size: 26rpx;
		color: $u-tips-color;
		margin-left: 10rpx;
	}

	.u-tab-view {
		width: 173rpx;
		min-width: 173rpx;
		height: 100%;
	}

	.u-tab-item {
		// height: 110rpx;
		// background: #F1F1F1;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 26rpx;
		color: #444;
		font-weight: 400;
		line-height: 1;
		color: #333333;
		padding: 18rpx 0;
		overflow: hidden;
	}

	.u-tab-item-active {
		margin: 0;
		position: relative;
		color: #48A147;
		font-size: 28rpx;
		font-weight: 500;
		background: #fff;
		background-color: white;
	}

	.u-tab-item-active::before {
		content: "";
		position: absolute;
		left: 0;
		width: 10rpx;
		height: 48rpx;
		background: linear-gradient(90deg, #48A147 0%, #8AE38A 100%);
		border-radius: 22rpx 22rpx 22rpx 22rpx;
	}

	.u-tab-view {
		height: 100%;
	}

	.right-box {
		background-color: white;
	}

	.page-view {
		// padding: 16rpx;
		background: #fff;
	}

	.class-item {
		margin-bottom: 30rpx;
		background-color: #fff;
		padding: 16rpx;
		border-radius: 8rpx;
		padding-top: 0;
	}

	.class-item:last-child {
		// min-height: 100vh;
	}

	.item-title {
		font-size: 26rpx;
		color: $u-main-color;
		font-weight: bold;
	}

	.item-menu-name {
		font-weight: normal;
		font-size: 24rpx;
		color: $u-main-color;
	}

	.item-container {
		display: flex;
		flex-wrap: wrap;

		&-item {
			padding: 20rpx 0;
			width: 100%;
			border-bottom: 2rpx dashed #E5E5E5;
			padding-top: 0;
		}

		.title {
			width: 380rpx;
			font-size: 28rpx;
			font-family: PingFang SC-Bold, PingFang SC;
			font-weight: bold;
			color: #333333;
			line-height: 36rpx;
		}


		.goods-tag {
			font-size: 24rpx;
			font-family: PingFang SC-Regular, PingFang SC;
			font-weight: 400;
			color: #666666;
		}

		.price-box {
			>.price {
				color: #EF2929;
				font-size: 30rpx;
				font-family: PingFang SC-Bold, PingFang SC;
			}

			>.unit {}

			>.old-price {
				color: #999999;
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 400;
				text-decoration: line-through;
			}
		}
	}

	.thumb-box {
		width: 33.333333%;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		margin-top: 20rpx;
	}

	.item-menu-image {
		width: 120rpx;
		height: 120rpx;
	}

	.info-box {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.empty-img-sale {
		width: 150rpx;
		height: 150rpx;
		background-color: red;
		border-radius: 10rpx;
		background-color: #ffffff94;
		top: 0;
		position: absolute;

		.sale-no-box {
			background: #333333a6;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			font-size: 22rpx;
			font-family: PingFang SC-Regular, PingFang SC;
			font-weight: 400;
			color: #FFFFFF;
			padding: 5rpx 15rpx;
			display: inline-block;

		}
	}

	.sale-num {
		background: #EF2929;
		bottom: 0;
		width: 150rpx;
		height: 32rpx;
		overflow: hidden;
		color: white;
		font-size: 22rpx;
		border-radius: 0 0 10rpx 10rpx;
	}
</style>